<template>
  <div class="login-container">
    <router-link to="/login" class="admin-login-link">用户登录</router-link>
    <div class="login-box">
      <h2>用户微信登录</h2>
      <!-- 微信登录专用容器 -->
      <div 
        id="wx_login_container" 
        v-if="!loading && !error"
        class="wx-login-wrapper"
      ></div>

      <!-- 添加的文字说明 -->
      <div v-if="!loading && !error" class="wechat-tips">
        <p>使用微信扫一扫登录</p>
        <p>“图易通”</p>
      </div>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-text">
        <span class="dot-flashing"></span>
        正在加载安全组件...
      </div>

      <!-- 错误提示 -->
      <p v-if="error" class="error-text">{{ error }}</p>

    </div>
    <!-- 模拟登录按钮 -->
    <div v-if="isDevMode" class="dev-mode-btn">
      <button @click="simulateLogin">模拟登录成功</button>
    </div>
    <div v-if="isDevMode" class="dev-mode-btn">
      <button @click="simulateSuperLogin">模拟超级管理员登录成功</button>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {

  name: 'LoginView',
  data() {
    return {
      loading: true,
      error: null,
      retryCount: 0,
      maxRetries: 3,
      isDevMode:true //模拟登录按钮
    };
  },
  methods: {
    // 初始化微信登录
    async initWechatLogin() {
      try {
        // 检查微信SDK是否已加载
        if (!window.WxLogin) {
          throw new Error('WeChat SDK not loaded.');
        }

        // 1. 获取后端配置参数
        const { data } = await axios.get('/api/login/init');
        const { 
          appId='',
          redirectUri='',
          scope = "snsapi_login", 
          state = Date.now().toString(36) 
        } = data.data;
        console.log("appid:"+appId+",redirect_uri:"+redirectUri+",state:"+state);

        // 2. 确保容器存在
        await this.$nextTick();

        // 调试信息：检查容器是否存在
        const container = document.getElementById('wx_login_container');
        if (!container) {
          throw new Error('Container not found for WxLogin initialization.');
        }

        // 3. 初始化微信登录组件
        new window.WxLogin({
          self_redirect: true,    // 自动跳转模式
          id: 'wx_login_container',
          appid: 'wxbdc5610cc59c1631',//appId
          scope: scope,
          redirect_uri: encodeURIComponent('https://passport.yhd.com/wechat/callback.do'),// encodeURIComponent(redirectUri+'/login/admin')
          state: state,
          style: 'black',          // 按钮样式：black/white
          href: this.generateStyle() // 自定义样式
        });

        console.log('WxLogin initialized successfully.');

      } catch (err) {
        console.error('Error initializing WeChat login:', err);
        this.handleError(err);
      }
    },

    // 生成自定义样式（Base64编码）
    generateStyle() {
      const css = `
        .impowerBox .title { display: none; }
        .impowerBox .qrcode { margin-top: 0; }
        .impowerBox .info { display: none; }
      `;
      return `data:text/css;base64,${window.btoa(css)}`;
    },

    // 错误处理
    handleError(err) {
      if (this.retryCount < this.maxRetries) {
        this.retryCount++;
        setTimeout(() => this.initWechatLogin(), 1000);
        this.error = `正在尝试重新连接 (${this.retryCount}/${this.maxRetries})`;
      } else {
        this.error = '无法加载登录组件，请检查网络或联系管理员' + err;
        this.loading = false;
      }
    },
     // 模拟登录成功的方法
    async simulateLogin() {
      try {
        // 在这里你可以选择直接跳转到主页或调用一个特定的API来模拟登录成功
        // 这里假设有一个专门用于测试的API接口
        const response = await axios.get('/api/login/admin/simulateLogin');
        
        if(response.status == 200) {
          // 模拟登录成功后的操作，比如重定向到主页
          window.location.href = '/adminHome/orderList';
        }
      } catch (err) {
        console.error('Failed to simulate login:', err);
      }
    },
    async simulateSuperLogin() {
      try {
        // 在这里你可以选择直接跳转到主页或调用一个特定的API来模拟登录成功
        // 这里假设有一个专门用于测试的API接口
        const response = await axios.get('/api/login/superAdmin/simulateLogin');
        
        if(response.status == 200) {
          // 模拟登录成功后的操作，比如重定向到主页
          window.location.href = '/adminHome/orderList';
        }
      } catch (err) {
        console.error('Failed to simulate login:', err);
      }
    },
  },
  async mounted() {
    if (location.href.indexOf("#reloaded") == -1) {
        location.href = location.href + "#reloaded";
        location.reload();
    }
    try {
      // 动态加载微信SDK
      if (!window.WxLogin) {
        const script = document.createElement('script');
        script.src = 'https://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js';
        script.onload = () => {
          this.initWechatLogin();
        };
        script.onerror = () => {
          this.error = 'Failed to load WeChat SDK.';
          this.loading = false;
        };
        document.body.appendChild(script);
      } else {
        await this.initWechatLogin();
      }

      // 关闭加载状态
      this.loading = false;

    } catch (err) {
      this.handleError(err);
    }
  },
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: #304156;
  padding: 20px;
}

.login-box {
  width: 100%;
  max-width: 380px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
  padding: 40px 30px;
}

h2 {
  text-align: center;
  color: #1a1a1a;
  margin-bottom: 30px;
  font-size: 24px;
}

.wx-login-wrapper {
  min-height: 300px; /* 微信二维码容器最小高度 */
  display: flex;
  justify-content: center;
}

.loading-text {
  text-align: center;
  color: #666;
  margin: 30px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.error-text {
  color: #ff4d4f;
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
}

/* 加载动画 */
.dot-flashing {
  position: relative;
  width: 6px;
  height: 6px;
  border-radius: 3px;
  background-color: #1890ff;
  animation: dotFlashing 1s infinite linear alternate;
  animation-delay: 0.5s;
}

.dot-flashing::before,
.dot-flashing::after {
  content: '';
  display: inline-block;
  position: absolute;
  top: 0;
}

.dot-flashing::before {
  left: -10px;
  width: 6px;
  height: 6px;
  border-radius: 3px;
  background-color: #1890ff;
  animation: dotFlashing 1s infinite alternate;
  animation-delay: 0s;
}

.dot-flashing::after {
  left: 10px;
  width: 6px;
  height: 6px;
  border-radius: 3px;
  background-color: #1890ff;
  animation: dotFlashing 1s infinite alternate;
  animation-delay: 1s;
}

@keyframes dotFlashing {
  0% { background-color: #1890ff; }
  50%,
  100% { background-color: rgba(24, 144, 255, 0.2); }
}

.wx-login-wrapper {
  min-height: 300px;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
}

.wechat-tips {
  text-align: center;
  margin-top: 16px;
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

.admin-login-link {
  position: absolute;
  top: 20px;
  right: 20px;
  text-decoration: none;
  font-size: 14px;
  color: #bfcbd9;
  background-color: #304156;
  border: 1px solid #91d5ff;
  padding: 8px 16px;
  border-radius: 4px;
  transition: all 0.3s ease;
}
</style>